package com.freeter.modules.cityrecord.controller;

import com.freeter.common.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: jinjueYang
 * Date: 2019/4/11
 * Time: 10:54
 * Description:
 */
@Controller
@RequestMapping("cityrecord/upload")
public class UploadController {
    @Value("${file_path}")
    private String filePath;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @RequestMapping("fileupload")
    @ResponseBody
    public R fileUpload(MultipartFile file) {
        String fileName = file.getOriginalFilename();

        File parentDir = new File(filePath);
        if (!parentDir.exists()) //如果那个目录不存在先创建目录
        {
            parentDir.mkdir();
        }
        String fileUidName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        try {
            file.transferTo(new File(filePath + fileUidName));
        } catch (IOException e) {
            e.printStackTrace();
            R.error("文件上传失败!");
        }
        return R.ok().put("data", fileUidName);
    }
}
